package com.lib.online.controller;


import java.io.IOException;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.lib.online.model.Reading;
import com.lib.online.model.User;

import com.lib.online.service.BookService;
import com.lib.online.service.UserService;



/**
 * @author Ievgen_S
 * Handles requests for the application home page.
 */
@Controller
@SessionAttributes("curUser")
public class BookController {
		
	  @Autowired
		BookService bookService;
	  @Autowired
	    UserService userService;
	  @Autowired
		private SessionFactory sessionFactory;
	  
	   	  
	  
		@InitBinder
		public void initBinder(WebDataBinder webDataBinder) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
			dateFormat.setLenient(false);
			webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		}
	  
	  @RequestMapping("/")
	  public String welcome(){	   
	  
	    return "forward:/browse";
	    
	  }
	  
	  @RequestMapping(value = "init_upload", method = {RequestMethod.POST, RequestMethod.GET})
	  public String uploadInit(Model model){	   
	      model.addAttribute("book", new Reading());
	    return "upload";
	    
	  }
	  
	  
	  
	  	  
		  @RequestMapping(value = "browse", method = {RequestMethod.POST, RequestMethod.GET})  
		   public String getAllBooks(Model model) {
		        List<Reading> books = this.bookService.getAllBooks();
		        model.addAttribute("books", books);
		        
		        return "index";
		    }
		  
		  @RequestMapping(value = "browse/random", method = RequestMethod.GET)  
		   public String getRandBook(Model model) {
		        Reading book = this.bookService.randomBook();
		       
		        model.addAttribute("book", book);
		       		        
		        return "bookDetails";
		    }
		  
		  @RequestMapping(value = "browse/sorted", method = RequestMethod.GET)  
		   public String getSortedBooks(Model model) {
		        List<Reading> books = this.bookService.nameSortedBooks();
		        model.addAttribute("books", books);
		        return "index";
		    }
		  
		  @RequestMapping(value = "book/{title}", method = RequestMethod.GET)  
		   public String getBookDetails(@PathVariable String title, Model model) {
			  Reading book = this.bookService.getBook(title);		       
		        model.addAttribute("book", book);		       
		        return "bookDetails";
		    }
		  
		  @RequestMapping(value = "/upload", method = RequestMethod.POST)
		  public  String uploadBook(@ModelAttribute("book") Reading newBook, BindingResult br,
		  @RequestParam("file") CommonsMultipartFile file, Model model) {
	        		      
		  if (br.hasErrors()) {
			
			return "upload";
		}
		  
		  User user = (User) model.asMap().get("curUser");
		  
			 if (user!=null) {				  
		 if (!file.isEmpty() && file!=null && newBook!=null) {
		     
		     Blob blob = Hibernate.getLobCreator(sessionFactory.openSession()).createBlob(file.getBytes());
		    		    
			  newBook.setData(blob);
			  newBook.setContent_type(file.getContentType());			 		  
		 bookService.uploadBook(newBook);
			 userService.addUserBook(newBook.getTitle(), user);	
		 model.addAttribute("message", "Book was uploaded and added successfully!");
		 } else {
		     model.addAttribute("message", "Problems while uploading!");
		     return "upload";
		     }		
		   } 
		  return "redirect:/browse";
		  }
		  
		  @RequestMapping("/download/{title}")
		  public String downloadBook(@PathVariable("title") String title,
		  HttpServletResponse response) {

		      Reading book = this.bookService.getBook(title);	
		  try {
		  response.setHeader("Content-Disposition", "inline;filename=\""
		  + title + ".txt" + "\"");
		  OutputStream out = response.getOutputStream();
		  response.setContentType(book.getContent_type());
		  IOUtils.copy(book.getData().getBinaryStream(), out);
		  out.flush();
		  out.close();
		 

		  } catch (IOException e) {
		  e.printStackTrace();
		  } catch (SQLException e) {
		  e.printStackTrace();
		  }

		  return null;
		  }

	  
	
}
